<?php
/**
 * link: http://bbs.52jscn.com
 * copyright: Copyright (c) 2018 人人禾匠商城
 * author: jack_guo
 */

namespace app\forms\mall\export;

use app\core\CsvExport;

class ShareStatisticsExport extends BaseExport
{

    public function fieldsList()
    {
        return [
            [
                'key' => 'id',
                'value' => 'ID',
            ],
            [
                'key' => 'nickname',
                'value' => '分销商',
            ],
            [
                'key' => 'first_children',
                'value' => '直接下级数量',
            ],
            [
                'key' => 'all_children',
                'value' => '总下级数量',
            ],
            [
                'key' => 'all_order',
                'value' => '分销商订单数',
            ],
            [
                'key' => 'all_money',
                'value' => '总佣金',
            ],
            [
                'key' => 'total_money',
                'value' => '累计佣金',
            ],
            [
                'key' => 'price',
                'value' => '已提现佣金',
            ],
        ];
    }

    public function export($query)
    {
        $list = $query->with('user.userInfo')
            ->asArray()
            ->all();

        foreach ($list as $key => $value) {
            $list[$key]['nickname'] = $value['user']['nickname'];
            $list[$key]['avatar'] = $value['user']['userInfo']['avatar'];
            unset($list[$key]['user']);
        }
        
        $this->transform($list);
        $this->getFields();
        $dataList = $this->getDataList();

        $fileName = '分销排行' . date('YmdHis');
        (new CsvExport())->export($dataList, $this->fieldsNameList, $fileName);
    }

    protected function transform($list)
    {
        $newList = [];
        $arr = [];

        $number = 1;
        foreach ($list as $key => $item) {
            $arr['number'] = $number++;
            $item['first_children'] = intval($item['first_children']);
            $item['all_children'] = intval($item['all_children']);
            $item['all_order'] = intval($item['all_order']);
            $item['all_money'] = floatval($item['all_money']);
            $item['total_money'] = floatval($item['total_money']);
            $item['price'] = floatval($item['price']);

            $arr = array_merge($arr, $item);

            $newList[] = $arr;
        }
        $this->dataList = $newList;
    }

    protected function getFields()
    {
        $arr = [];
        foreach ($this->fieldsList() as $key => $item) {
            $arr[$key] = $item['key'];
        }
        $this->fieldsKeyList = $arr;
        parent::getFields(); // TODO: Change the autogenerated stub
    }
}
